{%- set separator = ' ' -%}
#!/usr/bin/env dash
{{ pillar['headers']['multiline'] -}}
. /usr/share/openmediavault/scripts/helper-functions

set -e

# Make sure that only one instance of this shell script is running at
# the same time.
LOCK_FILE=/run/openmediavault-iptables.lock
if ! mkdir "${LOCK_FILE}"; then
    omv_error "Locking failed, another job is running"
    exit 0
fi

trap "rm -rf ${LOCK_FILE}" 0 1 2 3 5 15

case "$1" in
    start)
        {% if num_inet_rules > 0 -%}
        iptables -t filter -F INPUT
        iptables -t filter -F OUTPUT
        {% endif -%}
        {%- if num_inet6_rules > 0 -%}
        ip6tables -t filter -F INPUT
        ip6tables -t filter -F OUTPUT
        {% endif -%}

        {%- for rule in rules | sort(attribute='family') | sort(attribute='rulenum') %}
        {%- if rule.family == 'inet' %}iptables{% endif -%}
        {%- if rule.family == 'inet6' %}ip6tables{% endif -%}
        {{ separator }}-A {{ rule.chain }}
        {%- if rule.protocol.startswith('!') %} !{% endif %} -p {{ rule.protocol | replace('!', '') }}

        {%- if rule.source | length > 0 -%}
        {%- if '-' in rule.source -%}
        {{ separator }}--match iprange {% if rule.source.startswith('!') %}!{% endif %} --src-range {{ rule.source | replace('!', '') }}
        {%- else %}
        {%- if rule.source.startswith('!') %} !{% endif %} --source {{ rule.source | replace('!', '') }}
        {%- endif %}
        {%- endif %}

        {%- if rule.sport | length > 0 -%}
        {%- if rule.sport.startswith('!') %} !{% endif %} --sport {{ rule.sport | replace('!', '') | replace('-', ':') }}
        {%- endif %}

        {%- if rule.destination | length > 0 -%}
        {%- if '-' in rule.destination -%}
        {{ separator }}--match iprange {% if rule.destination.startswith('!') %}!{% endif %} --dst-range {{ rule.destination | replace('!', '') }}
        {%- else %}
        {%- if rule.destination.startswith('!') %} !{% endif %} --destination {{ rule.destination | replace('!', '') }}
        {%- endif %}
        {%- endif %}

        {%- if rule.dport | length > 0 -%}
        {%- if rule.dport.startswith('!') %} !{% endif %} --dport {{ rule.dport | replace('!', '') | replace('-', ':') }}
        {%- endif %}

        {%- if rule.action | length > 0 -%}
        {{ separator }}-j {{ rule.action }}
        {%- endif %}

        {%- if rule.extraoptions | length > 0 -%}
        {{ separator }}{{ rule.extraoptions }}
        {%- endif %}
        {% endfor -%}
        ;;

    stop)
        iptables -t filter -F INPUT
        iptables -t filter -F OUTPUT
        iptables -P INPUT ACCEPT
        iptables -P OUTPUT ACCEPT
        ip6tables -t filter -F INPUT
        ip6tables -t filter -F OUTPUT
        ip6tables -P INPUT ACCEPT
        ip6tables -P OUTPUT ACCEPT
        ;;
esac

exit 0
